<template>
  <div class="app-container">
    <el-card>
      <el-row>
        <p class="pinformation">搜索条件</p>
      </el-row>
      <el-form ref="queryRef" label-width="90" :model="queryParams" :inline="true">
        <el-form-item label="检测类别组：" prop="jclbGroupId">
          <el-select
            v-model="queryParams.jclbGroupId"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in jclbGroupList"
              :key="item.pJclbId"
              :value="item.pJclbId"
              :label="item.jclbGroupName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检测项目：" prop="jcxmName">
          <el-input
            clearable
            maxlength="100"
            placeholder="请输入检测项目"
            v-model.trim="queryParams.jcxmName"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleQuery">搜索</el-button>
          <el-button class="resetBtn" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row>
        <p class="pinformation" style="margin-top: 8px">数据列表</p>
        <p class="totalStyle" style="margin-top: 6px">共 {{ total }} 条数据</p>
        <el-row style="margin-left: 20px">
          <el-button link type="success" icon="Download" @click="handleExport"
            >导出样品合并表</el-button
          >
          <el-button link type="success" icon="Upload" @click="handleImport"
            >导入样品合并表</el-button
          >
        </el-row>
      </el-row>
      <el-table ref="mainTableRef" :data="fixerList" v-loading="loading">
        <el-table-column label="序号" width="70" align="center">
          <template #default="scope">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="检测类别组" prop="jclbGroupName" align="center" />
        <el-table-column
          label="检测项目"
          prop="jcxmNames"
          align="center"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span v-html="proxy.getSupAndSub(scope.row.jcxmNames)"></span>
          </template>
        </el-table-column>
        <el-table-column label="容器" align="center">
          <template #default="scope">
            <el-select
              v-model="scope.row.container"
              placeholder="请选择容器"
              clearable
              @change="submit({ id: scope.row.id, container: scope.row.container })"
            >
              <el-option
                v-for="dict in sys_sample_container"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="固定剂" align="center">
          <template #default="scope">
            <el-select
              v-model="scope.row.fixer"
              placeholder="请选择固定剂"
              clearable
              @change="submit({ id: scope.row.id, fixer: scope.row.fixer })"
            >
              <el-option
                v-for="dict in sys_fixer"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="固定剂要求" align="center">
          <template #default="scope">
            <el-select
              v-model="scope.row.fixerDesc"
              placeholder="请选择容器"
              clearable
              @change="submit({ id: scope.row.id, fixerDesc: scope.row.fixerDesc })"
            >
              <el-option
                v-for="dict in sys_fixer_desc"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="固定剂描述" align="center">
          <template #default="scope">
            <el-input
              maxlength="100"
              clearable
              placeholder="请输入固定剂描述"
              v-model="scope.row.fixerRemark"
              @change="submit({ id: scope.row.id, fixerRemark: scope.row.fixerRemark })"
            />
          </template>
        </el-table-column>
        <el-table-column label="默认容量" align="center">
          <template #default="scope">
            <el-input
              maxlength="100"
              clearable
              placeholder="请输入默认容量"
              v-model="scope.row.defaultCapacity"
              @change="
                submit({ id: scope.row.id, defaultCapacity: scope.row.defaultCapacity })
              "
            />
          </template>
        </el-table-column>
        <el-table-column label="保存要求" align="center">
          <template #default="scope">
            <el-input
              maxlength="100"
              clearable
              placeholder="请输入保存要求"
              v-model="scope.row.saveDesc"
              @change="submit({ id: scope.row.id, saveDesc: scope.row.saveDesc })"
            />
          </template>
        </el-table-column>
        <el-table-column label="保存时长" align="center" width="220px">
          <template #default="scope">
            <el-row>
              <el-input
                maxlength="100"
                clearable
                v-model="scope.row.saveTime"
                @change="submit({ id: scope.row.id, saveTime: scope.row.saveTime })"
                style="width: 35%"
              />&nbsp;
              <el-select
                v-model="scope.row.unitId"
                style="width: 63%"
                @change="submit({ id: scope.row.id, unitId: scope.row.unitId })"
                clearable
              >
                <el-option
                  v-for="dict in timeUnitList"
                  :key="dict.unitId"
                  :label="dict.unitName"
                  :value="dict.unitId"
                />
              </el-select>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="检测项目组" prop="groupName" align="center" />
        <el-table-column label="检测方法" align="center" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.methodCode
            }}<span v-html="proxy.getSupAndSub(scope.row.methodName)"></span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 导入对话框 -->
    <el-dialog
      :class="'el-dialog-theme3'"
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
      draggable
      :close-on-click-modal="false"
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="handleUploadError"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="success"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="handleExport"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="submitFileForm">确 定</el-button>
          <el-button type="danger" @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MethodFixerConfig">
import { getToken } from "@/utils/auth";
import { allListJclbGroup } from "@/api/store/jclb";
import { fixerSave, listFixer } from "@/api/basic/methodFixerConfig";
import { getUnitList } from "@/api/store/unit";

const { proxy } = getCurrentInstance();
const queryParams = ref({ pageNum: 1, pageSize: 10 });
const total = ref(0);
const fixerList = ref([]);
const loading = ref(false);
const { sys_sample_container, sys_fixer, sys_fixer_desc } = proxy.useShareDict(
  "sys_sample_container",
  "sys_fixer",
  "sys_fixer_desc"
);
const timeUnitList = ref([]);
const jclbGroupList = ref([]);
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

function getList() {
  loading.value = true;
  listFixer(queryParams.value).then((res) => {
    fixerList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  });
}

function submit(data) {
  if (data.orgUnitId == "") {
    data.orgUnitId = "-1";
  }
  fixerSave(data)
    .then(() => {
      proxy.$modal.msgSuccess("保存成功");
    })
    .catch((res) => {
      proxy.$modal.msgError("保存失败");
    });
}

function handleTimeUnitList() {
  getUnitList({ unitGroup: 4 }).then((res) => {
    timeUnitList.value = res.data;
  });
}
handleTimeUnitList();

getList();

allListJclbGroup(1).then((res) => {
  jclbGroupList.value = res.data;
});

// ---------------------表格自适应高度-----------------------
watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [{ tableName: "main", bottomHeight: 73 }];
    } else {
      heightParams.value = [{ tableName: "main", bottomHeight: 21 }];
    }
    getTableHeight();
  }
);

const heightParams = ref([{ tableName: "main", bottomHeight: 21 }]);

function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}

onMounted(() => {
  nextTick(function () {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  });
});

onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});
// -------------------导入模板逻辑-------------------
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/lims/store/fixer/importData",
});

/** 导入按钮操作 */
function handleImport() {
  upload.title = "样品合并导入";
  upload.open = true;
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "/lims/store/fixer/export",
    {
      ...queryParams.value,
    },
    `样品合并表_${new Date().getTime()}.xlsx`
  );
}

// 上传失败
function handleUploadError(err) {
  upload.isUploading = false;
  proxy.$modal.msgError("导入数据失败，原因：" + err.message);
}
</script>

<style></style>
